package drds.binlog.metadata;

import com.google.common.base.Function;
import com.google.common.collect.ComputingMap;
import drds.binlog.common.position.ClientInfo;
import drds.binlog.common.position.Position;
import drds.binlog.common.position.PositionRange;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 基于定时刷新的策略的mixed实现
 * <p>
 * <pre>
 * 几个优化：
 * 1. 去除batch数据刷新到zk中，切换时batch数据可忽略，重新从头开始获取
 * 2. cursor的更新，启用定时刷新，合并多次请求。如果最近没有变化则不更新
 * </pre>
 */
public class PeriodMixedMetaDataManager extends MemoryMetaDataManager implements MetaDataManager
{

    private static final Logger logger = LoggerFactory.getLogger(PeriodMixedMetaDataManager.class);
    @SuppressWarnings("serial")
    private final Position nullCursor = new Position()
    {
    };
    private ScheduledExecutorService executor;
    private ZooKeeperMetaDataManager zooKeeperMetaManager;
    private long period = 1000;                                                 // 单位ms
    private Set<ClientInfo> updateCursorTasks;

    public void start()
    {
        super.start();
        Assert.notNull(zooKeeperMetaManager);
        if (!zooKeeperMetaManager.isRunning())
        {
            zooKeeperMetaManager.start();
        }

        executor = Executors.newScheduledThreadPool(1);
        destinationToClientInfoListMap = ComputingMap.makeComputingMap(new Function<String, List<ClientInfo>>()
        {

            public List<ClientInfo> apply(String destination)
            {
                return zooKeeperMetaManager.getClientInfoList(destination);
            }
        });

        clientInfoToPositionMap = ComputingMap.makeComputingMap(new Function<ClientInfo, Position>()
        {

            public Position apply(ClientInfo clientInfo)
            {
                Position position = zooKeeperMetaManager.getPosition(clientInfo);
                if (position == null)
                {
                    return nullCursor; // 返回一个空对象标识，避免出现异常
                } else
                {
                    return position;
                }
            }
        });

        clientInfoToBatchIdToPositionRangeMapMap = ComputingMap.makeComputingMap(new Function<ClientInfo, BatchIdToPositionRangeConcurrentMap>()
        {

            public BatchIdToPositionRangeConcurrentMap apply(ClientInfo clientInfo)
            {
                // 读取一下zookeeper信息，初始化一次
                BatchIdToPositionRangeConcurrentMap batches = BatchIdToPositionRangeConcurrentMap.create(clientInfo);
                Map<Long, PositionRange> positionRanges = zooKeeperMetaManager.getBatchIdToPositionRangeMap(clientInfo);
                for (Map.Entry<Long, PositionRange> entry : positionRanges.entrySet())
                {
                    batches.addPositionRange(entry.getKey(), entry.getValue()); // 添加记录到指定batchId
                }
                return batches;
            }
        });

        updateCursorTasks = Collections.synchronizedSet(new HashSet<ClientInfo>());

        // 启动定时工作任务
        executor.scheduleAtFixedRate(new Runnable()
        {

            public void run()
            {
                List<ClientInfo> tasks = new ArrayList<ClientInfo>(updateCursorTasks);
                for (ClientInfo clientInfo : tasks)
                {
                    try
                    {
                        // 定时将内存中的最新值刷到zookeeper中，多次变更只刷一次
                        zooKeeperMetaManager.updatePosition(clientInfo, getPosition(clientInfo));
                        updateCursorTasks.remove(clientInfo);
                    } catch (Throwable e)
                    {
                        // ignore
                        logger.error("period update" + clientInfo.toString() + " curosr failed!", e);
                    }
                }
            }
        }, period, period, TimeUnit.MILLISECONDS);
    }

    public void stop()
    {
        super.stop();

        if (zooKeeperMetaManager.isRunning())
        {
            zooKeeperMetaManager.stop();
        }

        executor.shutdownNow();
        destinationToClientInfoListMap.clear();
        clientInfoToBatchIdToPositionRangeMapMap.clear();
    }

    public void subscribe(final ClientInfo clientInfo) throws MetaDataManagerException
    {
        super.subscribe(clientInfo);

        // 订阅信息频率发生比较低，不需要做定时merge处理
        executor.submit(new Runnable()
        {

            public void run()
            {
                zooKeeperMetaManager.subscribe(clientInfo);
            }
        });
    }

    public void unsubscribe(final ClientInfo clientInfo) throws MetaDataManagerException
    {
        super.unsubscribe(clientInfo);

        // 订阅信息频率发生比较低，不需要做定时merge处理
        executor.submit(new Runnable()
        {

            public void run()
            {
                zooKeeperMetaManager.unsubscribe(clientInfo);
            }
        });
    }

    public void updatePosition(ClientInfo clientInfo, Position position) throws MetaDataManagerException
    {
        super.updatePosition(clientInfo, position);
        updateCursorTasks.add(clientInfo);// 添加到任务队列中进行触发
    }

    public Position getPosition(ClientInfo clientInfo) throws MetaDataManagerException
    {
        Position position = super.getPosition(clientInfo);
        if (position == nullCursor)
        {
            return null;
        } else
        {
            return position;
        }
    }

    // =============== setter / getter ================

    public void setZooKeeperMetaManager(ZooKeeperMetaDataManager zooKeeperMetaManager)
    {
        this.zooKeeperMetaManager = zooKeeperMetaManager;
    }

    public void setPeriod(long period)
    {
        this.period = period;
    }

}
